import cv2
import numpy as np
import imutils
import pytesseract
pytesseract.pytesseract.tesseract_cmd=r'D:\GoogleOCR\tesseract.exe'

img = cv2.imread('carcard.jpg')
img = cv2.resize(img,(640,420),interpolation=cv2.INTER_LANCZOS4)
final_img = img
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 双边滤波模糊
gray_img = cv2.bilateralFilter(gray_img,3,45,45)
gray_img = cv2.Canny(gray_img,20,300)


# opencv2返回两个值：contours、hierarchy。opencv3返回三个值：img（图像）、countours（轮廓）、hierarchy（层次结构）
contours = cv2.findContours(gray_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# imutils.grab_contours的作用，返回cnts中的countors(轮廓)，不区分opencv2或opencv3
contours = imutils.grab_contours(contours)
# 想要过滤掉那些微小琐碎的轮廓，将findContours查找到的轮廓按照面积排序
contours = sorted(contours,key=cv2.contourArea, reverse = True)[0:10]
screenCnt = None

for c in contours:
    area = cv2.contourArea(c)
    print(area)
    epsilon = 0.02*cv2.arcLength(c,True)

    # approxPolyDP()返回值为四个顶点的坐标
    approx = cv2.approxPolyDP(c,epsilon,True)

    if len(approx) == 4:
      screenCnt = approx
      print(len(screenCnt))
      cv2.drawContours(img, [screenCnt], -1, (0, 0, 255), 1)

      break


# 创建蒙版
img_mask = np.zeros(gray_img.shape,np.uint8)
new_img = cv2.drawContours(img_mask,[screenCnt],0,255,-1)
img=cv2.bitwise_and(img,img,mask=new_img)
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

(x,y)=np.where(img_mask==255)
topx=np.max(x)
topy=np.max(y)
bottomx=np.min(x)
bottomy=np.min(y)
Cropped = np.zeros(gray_img.shape,np.uint8)
Cropped = cv2.rectangle(Cropped,(topy,topx),(bottomy,bottomx),255,1)
Cropped=img[bottomx:topx,bottomy:topy]
Cropped = cv2.resize(Cropped,(400,200),interpolation=cv2.INTER_LANCZOS4)

# 识别字符
text = pytesseract.image_to_string(Cropped,config='--psm 11')
print("Detected license plate number is:",text)
print(text[0:7])
cv2.drawContours(final_img, [screenCnt], -1, (0, 0, 255), 5)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(final_img,text[0:7],(bottomy,bottomx-10), font, 1,(0,0,255),2)

cv2.imshow('img',final_img)
cv2.waitKey()
cv2.destroyAllWindows()